package org.scboy.common.gen.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;

import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.ResourceLoader;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;


public class TemplateUtil {
	
	/**
	 * 渲染模板（Root:classes/gen/）
	 * @param tpl 模板路径
	 * @param data 数据
	 * @return
	 * @throws IOException
	 * @throws URISyntaxException 
	 */
	@SuppressWarnings("rawtypes")
	public static String render(String tpl,Map<String, Object> data) throws Exception{
		ResourceLoader resourceLoader =new FileResourceLoader(Template.class.getResource("/gen").toURI().getPath());
		Configuration cfg = Configuration.defaultConfiguration();
		GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
		Template t = gt.getTemplate(tpl);
		t.binding(data);
		String str = t.render();
		return str;
	}
	
	/**
	 * 创建文件
	 * @param filePatch 文件路径
	 * @param fileName 文件名
	 * @param context 文件内容
	 * @throws IOException 
	 */
	public static void createFile(String filePatch,String fileName,String context) throws IOException{
		//检查文件夹是否创建
		File dir=new File(filePatch);
		if(!dir.exists()){
			dir.mkdirs();
		}
		File file=new File(filePatch+"\\"+fileName);
		FileWriter writer = new FileWriter(file);
		writer.write(context);;
		writer.close();
	}
	
}
